using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class  AutoHotfixInjectEditor : AssetPostprocessor {
	static AutoHotfixInjectEditor() {
		EditorApplication.update += Update;
	} 
	
	public static void OnPostprocessAllAssets(
		string[] importedAssets,
		string[] deletedAssets,
		string[] movedAssets,
		string[] movedFromAssetPaths)
	{
		#if !HOTFIX_ENABLE
		return;
		#endif
		compileEnd = false;
		tick = 5;
		foreach(string str in importedAssets) 
		{
			if (str.EndsWith(".cs"))
			{
				PlayerPrefs.SetInt("ImportScripts", 1);
				break;
			}
		}
	}

	private static bool compileEnd = false;
	private static float tick = 5;
	private static void Update() {
#if !HOTFIX_ENABLE
		return;
#endif
		if (compileEnd)
		{
			tick -= Time.deltaTime;
			if(tick < 0)
			{
				compileEnd = false;
				EditorApplication.update -= Update;
				OnUnityScripsCompilingCompleted();
			}
			return;
		}
		bool importScripts = Convert.ToBoolean(PlayerPrefs.GetInt("ImportScripts", 1));
		if (importScripts && !EditorApplication.isCompiling) {
			//OnUnityScripsCompilingCompleted();
			importScripts = false;
			PlayerPrefs.SetInt("ImportScripts", 0);
			compileEnd = true;
		}
	}
 
	private static void OnUnityScripsCompilingCompleted() {
#if HOTFIX_ENABLE
		DirectoryInfo fi = new DirectoryInfo(CSObjectWrapEditor.GeneratorConfig.common_path);
		if(!fi.Exists)
			return;
		Debug.Log("Auto Hotfix Inject Editor");
		XLua.Hotfix.HotfixInject();
#endif
	}
}
